package com.basics.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import com.basics.common.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 接口请求
 *--------------------------------------------------->
 * @Author WangWei
 * @date 2018年8月17日 上午9:36:27
 * @version V1.0
 * @Email 1246518873@qq.com
 *--------------------------------------------------->
 * @Description:
 *
 *
 */
public class HttpRequest {

	static Log log = LogFactory.getLog(HttpRequest.class);


	public static String sendGet(String url){
		StringBuffer buffer = new StringBuffer();
		try {
			URL serverUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
			conn.setRequestMethod("GET");
			//必须设置false，否则会自动redirect到重定向后的地址
			conn.setInstanceFollowRedirects(false);
			conn.addRequestProperty("Accept-Charset", "UTF-8;");
			conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
			conn.addRequestProperty("Referer", "https://m.dimoclub.com/");
			conn.connect();

			//判定是否会进行302重定向
			if (conn.getResponseCode() == 302) {
				//如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
				String location = conn.getHeaderField("Location");
				String cookies = conn.getHeaderField("Set-Cookie");

				serverUrl = new URL(location);
				conn = (HttpURLConnection) serverUrl.openConnection();
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Cookie", cookies);
				conn.addRequestProperty("Accept-Charset", "UTF-8;");
				conn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
				conn.addRequestProperty("Referer", "http://m.dimoclub.com/");
				conn.connect();
			}

			//将返回的输入流转换成字符串
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param,String charset) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			if (StringUtils.isNotBlank(param)) {
				urlNameString = url + "?" + param;
			}
			log.error("GET "+urlNameString);
			URL realUrl = new URL(urlNameString);
			//SSLUtils.setSSL();
			// 打开和URL之间的连接
			URLConnection connection = HttpRequestUtil.getConnection("GET", realUrl);;
			// 设置通用的请求属性
			connection.setRequestProperty("Accept", "*/*");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection
					.setRequestProperty(
							"User-agent",
							"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36");
			connection.setRequestProperty("Referer",
					"http://info.sporttery.cn/wechat/");
			connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			connection.setRequestProperty("Accept-Encoding",
					"deflate, sdch");
			connection.setRequestProperty("Cache-Control", "max-age=0");
			connection
					.setRequestProperty(
							"Cookie",
							"BIGipServerPool_apache_web=1224802570.20480.0000; Hm_lvt_860f3361e3ed9c994816101d37900758=1446550156,1446694723,1447759021,1447903576; Hm_lpvt_860f3361e3ed9c994816101d37900758=1447912833");
			connection.setRequestProperty("Host", "i.sporttery.cn");
			connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			// Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(),charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！url="+url+" " + e.getMessage() );
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}


	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			log.error("POST "+url+",param="+param);
			 //SSLUtils.setSSL();
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = HttpRequestUtil.getConnection("POST", realUrl);;
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(),"utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！url="+url+" " + e.getMessage());
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		String js1 = sendGet("https://www.xiaomcc.com/json/100000.json",null, "UTF-8");
		 System.out.println(js1);
	}
	/**
	 * 发起https请求并获取结果
	 *
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
	    JSONObject jsonObject = null;
	    StringBuffer buffer = new StringBuffer();
	    try {
	        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
	    	SSLUtils.setSSL();

	        URL url = new URL(requestUrl);
	        HttpURLConnection httpUrlConn = HttpRequestUtil.getConnection(requestMethod, url);

	        httpUrlConn.setDoOutput(true);
	        httpUrlConn.setDoInput(true);
	        httpUrlConn.setUseCaches(false);
	        // 设置请求方式（GET/POST）
	        httpUrlConn.setRequestMethod(requestMethod);

	        if ("GET".equalsIgnoreCase(requestMethod)){
                httpUrlConn.connect();
            }


	        // 当有数据需要提交时
	        if (null != outputStr) {
	            OutputStream outputStream = httpUrlConn.getOutputStream();
	            // 注意编码格式，防止中文乱码
	            outputStream.write(outputStr.getBytes("UTF-8"));
	            outputStream.close();
	        }
	        long end = System.currentTimeMillis();
	        // 将返回的输入流转换成字符串
	        InputStream inputStream = httpUrlConn.getInputStream();
	        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
	        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

	        String str = null;
	        while ((str = bufferedReader.readLine()) != null) {
	            buffer.append(str);
	        }
	        bufferedReader.close();
	        inputStreamReader.close();
	        // 释放资源
	        inputStream.close();
	        inputStream = null;
	        httpUrlConn.disconnect();
	        jsonObject = JSONObject.parseObject(buffer.toString());
	    } catch (ConnectException ce) {
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	    return jsonObject;
	}


	public static String sendPost2(String url, String data) {
		String response = null;

		try {
			CloseableHttpClient httpclient = null;
			CloseableHttpResponse httpresponse = null;
			try {
				httpclient = HttpClients.createDefault();
				HttpPost httppost = new HttpPost(url);
				StringEntity stringentity = new StringEntity(data,
						ContentType.create("application/json", "UTF-8"));
				httppost.setEntity(stringentity);
				httpresponse = httpclient.execute(httppost);
				response = EntityUtils
						.toString(httpresponse.getEntity());

			} finally {
				if (httpclient != null) {
					httpclient.close();
				}
				if (httpresponse != null) {
					httpresponse.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}


}
